import React, { Component } from "react";
import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button/index";
import { connect } from "react-redux";
import { createForm } from "rc-form";
import { InputItem, Toast, Modal } from "antd-mobile";
import "./index.scss";
import verCode from "@component/verCode/index";
import BankItem from "./bankItem.js";
import { getAllSupportedBankList } from "@redux/Action/bankManage/bankManage";
import { getSupportedBankList } from "@redux/Action/bank/bank";
import { InterfaceG } from "@config/Config";
import BackModal from "@component/backModal/index";
import yhTools from "@tools/yh";
const BankIcon = require("../../../../images/icon-xj1.png");

const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkBankReg = value => /^\d{13,19}$/.test(value);

const agreementPageMap = {
	huaTongAccount: "/huaTongBankElectronicAccountServiceAgreement",
	taxStatement: "/individualTaxResidentStatusStatement",
	pay: "/agreementoflianyintong"
};

const backHomeMap = {
	601: "/xhfHomeNoCredit",
	802: "/xhdHome",
	1: "/walletHome",
	602: "/xhfHomeNoCredit"
};

const year = new Date().getFullYear();
const month = new Date().getMonth() + 1;
const day = new Date().getDate();
const getDocumentHeight = () => {
	return document.documentElement.clientHeight || document.body.clientHeight;
};
const originalHeight = getDocumentHeight();
@verCode()
@connect(
	state => ({
		supportedBankList: state.bankManageReducer.supportedBankList || [],
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		userName: state.bankManageReducer.userName,
		userRealNo: state.bankManageReducer.userRealNo
	}),
	dispatch => ({
		getAllSupportedBankList: value => dispatch(getAllSupportedBankList(value)),
		getSupportedBankList: (value, fun) =>
			dispatch(getSupportedBankList(value, fun))
	})
)
class BankManageAdd extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isVisible: false,
			userName: "", //用户姓名
			accountNo: "", //银行卡号
			verifyCode: "", //验证码
			idCard: "", //身份证号码
			userBankPhone: "", //银行预留手机号
			messageSerialNumber: "",
			verifier: "",
			isBackModalVisible: false,
			hasSendCode: false,
			canSubmit: true,
			isDesable: false,
			quickShow: false,
			quckBankList: [],
			isHiddenBotton: false,
			isCloseQuickShow: false
		};
	}
	async componentDidMount() {
		window.addEventListener("resize", this.resize);
		this.props.getSupportedBankList({ channelCode: "ll" });
		this.queryBankCardList();
		this.xhdQueryTwoElement();
	}
	resize = () => {
		const { quckBankList, isCloseQuickShow } = this.state;
		if (window.innerHeight !== originalHeight) {
			this.setState({
				quickShow: false,
				isHiddenBotton: true
			});
		} else {
			this.setState({
				quickShow: !isCloseQuickShow && quckBankList && quckBankList.length > 0,
				isHiddenBotton: false
			});
		}
	};
	componentWillUnmount() {
		window.removeEventListener("resize", this.resize);
	}
	xhdQueryTwoElement = () => {
		let objs = {
			url: InterfaceG.xhdQueryTwoElement,
			params: {},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			if (res.code == "0" && res.data.userName) {
				this.props.form.setFieldsValue({
					userName: res.data.userName,
					idCard: res.data.idNo
				});
				this.setState({
					// userName: res.data.userName,
					// idCard: res.data.idNo,
					isDesable: true
				});
			}
		});
	};
	toggleVisible = isVisible => {
		this.setState({
			isVisible
		});
	};
	queryBankCardList = () => {
		let objs = {
			url: InterfaceG.bankManageList,
			params: {
				channelCode: "ll",
				cardType: "2",
				delFlag: "1"
			},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			if (res.code == "0") {
				if (res.data && res.data.length > 0) {
					this.setState({
						quickShow: true,
						quckBankList: res.data
					});
				}
			}
		});
	};
	/**
	 * 发送验证码
	 */
	getMsgCode = () => {
		this.sendMsgCode();
	};
	sendMsgCode = () => {
		const { getFieldsValue } = this.props.form;
		let {
			userBankPhone = "",
			accountNo = "",
			userName = "",
			idCard = ""
		} = getFieldsValue(["userBankPhone", "accountNo", "userName", "idCard"]);
		userBankPhone = submitCardRegexp(userBankPhone);
		accountNo = submitCardRegexp(accountNo);
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		if (!accountNo) {
			Toast.info("请填写银行卡号", 2);
			return false;
		}
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(userBankPhone))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(60);
		let objs = {
			//url: InterfaceG.addBankSendMessage,
			url: InterfaceG.sendBindCardVerifyCode,
			params: {
				userName: userName,
				cardId: idCard,
				accountNo: accountNo,
				mobilePhone: userBankPhone,
				scene: "03" //"01", "还款绑卡","02", "借款绑卡","03", "银行卡管理绑卡","04", "实名认证绑卡","05", "授信申请绑卡"
			},
			_alertShow: false
		};
		Toast.loading("发送中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode(); //将组件的状态设置为发送成功倒计时状态
				//const { messageSerialNumber, verifier } = res.data;
				// this.setState({
				// 	messageSerialNumber,
				// 	verifier,
				// 	hasSendCode: true
				// });
				const { orderNo } = res.data;
				this.setState({
					orderNo,
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	/**
	 * 格式校验
	 */
	InputOnChange = (key, value) => {
		this.setState({
			[key]: submitCardRegexp(value)
		});
	};
	inputOnChangeCard = (key, value) => {
		this.setState({
			[key]: value
		});
	};
	/**
	 * 参数校验
	 */
	checkCanSubmit = (cardNo, phoneNum, verifyCode, idCard, userName) => {
		if (!userName) {
			Toast.info("请输入姓名", 2);
			return false;
		}
		if (!cardNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(cardNo)) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		if (!idCard) {
			Toast.info("请输入身份证号", 2);
			return false;
		}
		// if (!checkTheIdCard(idCard) && !isDesable) {
		// 	Toast.info("身份证号格式错误", 2);
		// 	return false;
		// }
		if (!phoneNum) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(phoneNum)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!this.state.hasSendCode) {
			Toast.info("请获取验证码", 2);
			return false;
		}
		if (!verifyCode.length) {
			Toast.info("请输入验证码");
			return false;
		}
		if (verifyCode.length !== 6) {
			Toast.info("验证码输入错误");
			return false;
		}
		return true;
	};
	updateBank = () => {
		this.chooseImage();
	};
	/**
	 * 选择图片
	 */
	chooseImage() {
		//打开原生获取图片
		let imgPicker = {
			type: "3", //相机和相册
			imageName: this.props.mobile + "_card_" + ".png",
			imageSize: 100 * 1024 + "", // 100kb,自定义
			thumbnailSize: 100 * 1024 + "" // 100kb,自定义
		};

		yhTools.chooseImage(imgPicker).then(
			resp => {
				this.getOcrBank(resp.data.path);
			},
			() => {}
		);
	}
	//获取ocr银行卡
	getOcrBank(path) {
		const imageData = {
			name: "bankImg.jpeg",
			path: path,
			params: {}
		};
		const objs = {
			url: InterfaceG.orcBank,
			imageArray: [imageData]
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				console.log('ocr信息：',res.data);
				this.InputOnChange("accountNo", res.data.cardNumber);
				const { setFieldsValue } = this.props.form;
				setFieldsValue({
					accountNo:res.data.cardNumber
				})
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	addNewBank = async () => {
		const { verifier, messageSerialNumber, orderNo } = this.state;

		const { getFieldsValue } = this.props.form;
		let {
			userBankPhone = "",
			accountNo = "",
			userName = "",
			idCard = "",
			verifyCode = ""
		} = getFieldsValue([
			"userBankPhone",
			"accountNo",
			"userName",
			"idCard",
			"verifyCode"
		]);
		userBankPhone = submitCardRegexp(userBankPhone);
		accountNo = submitCardRegexp(accountNo);
		if (
			this.checkCanSubmit(
				accountNo,
				userBankPhone,
				verifyCode,
				idCard,
				userName
			)
		) {
			let objs = {
				//url: InterfaceG.manageAddBankCard,
				url: InterfaceG.loanBindCard,
				params: {
					orderNo: orderNo,
					verifier: verifier,
					verifyCode: verifyCode,
					messageSerialNumber: messageSerialNumber,
					userBankPhone: userBankPhone,
					accountNo: accountNo,
					userName: userName,
					cardId: idCard,
					channelCode: "ll",
					productNum: "601",
					scene: "03" //"01", "还款绑卡","02", "借款绑卡","03", "银行卡管理绑卡","04", "实名认证绑卡","05", "授信申请绑卡"
				},
				_alertShow: false
			};
			Toast.loading("绑定中...", 2);
			yhTools.request(objs).then(res => {
				Toast.hide();
				if (res.code === "0") {
					Toast.success("绑卡成功", 3);
					setTimeout(() => {
						this.props.history.go(-1);
					}, 3000);
				} else {
					Toast.info(res.message, 3);
				}
			});
		}
	};

	/**
	 * 确认添加银行卡
	 */
	saveBank = () => {
		this.addNewBank();
	};
	//查看协议
	openContract = (e, type) => {
		e.stopPropagation();
		const { userName, idCard } = this.state;
		const commonParams = {
			personName: userName,
			idCardCode: idCard,
			year,
			month,
			day
		};
		this.props.history.push({
			pathname: agreementPageMap[type],
			params: commonParams
		});
	};
	onModalClick = booleanValue => {
		this.setState({
			isBackModalVisible: false
		});
		!booleanValue && this.props.history.push(backHomeMap[this.props.lnid]);
	};
	inputOnChangePt = (key, value) => {
		this.setState({
			[key]: submitCardRegexp(value)
		});
	};
	showModal = () => {
		this.setState({
			isVisible: false,
			isBackModalVisible: true
		});
	};
	//关闭快速绑卡弹窗
	closeQuick = () => {
		this.setState({
			isCloseQuickShow: true,
			quickShow: false
		});
	};
	//快速绑定
	quickBandCard = item => {
		this.props.form.setFieldsValue({
			userName: item.accountName,
			idCard: item.idCard,
			accountNo: item.accountNo.replace(/\s/g, "").replace(/(.{4})/g, "$1 "),
			userBankPhone: item.userBankPhone.replace(
				/^(.{3})(.*)(.{4})$/,
				"$1 $2 $3"
			)
		});
	};
	render() {
		const {
			isVisible,
			isBackModalVisible,
			from,
			hasSendCode,
			isDesable,
			quickShow,
			quckBankList,
			isHiddenBotton
		} = this.state;
		const { supportedBankList, lnid } = this.props;
		const { getFieldProps } = this.props.form;
		const _pageParams = {
			header: {
				title: "添加银行卡"
			},
			isModal: from === "liveness",
			history: this.props.history
		};
		const { countDown, isClick } = this.props.verCode;
		return (
			<MainLayout pageParams={_pageParams} handleBack={this.showModal}>
				<BackModal
					product={lnid}
					isVisible={isBackModalVisible}
					onClick={this.onModalClick}
				/>
				<div className="adds-bank-container">
					{/* <p className="item-title">请进行实名认证</p> */}
					<InputItem
						type="text"
						className="my-input"
						placeholder="请输入您的真实姓名"
						disabled={isDesable}
						{...getFieldProps("userName")}
					>
						姓名
					</InputItem>
					<InputItem
						type="text"
						className="my-input"
						disabled={isDesable}
						placeholder="请输入您的身份证号码"
						{...getFieldProps("idCard")}
					>
						身份证号
					</InputItem>
					<p className="item-title">
						<span className="title">请添加本人银行卡</span>
						<span
							className="zhic-list"
							onClick={() => this.toggleVisible(true)}
						>
							支持银行列表
						</span>
					</p>
					{/* 23包括空格 */}
					<InputItem
						maxLength="23"
						className="my-input my-clear1"
						placeholder="请输入银行卡号"
						type="bankCard"
						clear
						{...getFieldProps("accountNo")}
					>
						银行卡号
						<img
							alt="guide"
							className="icon-help"
							src={BankIcon}
							onClick={this.updateBank}
						/>
					</InputItem>
					<InputItem
						clear
						type="phone"
						placeholder="请输入银行预留手机号"
						className="my-input"
						{...getFieldProps("userBankPhone")}
					>
						手机号
					</InputItem>
					<InputItem
						clear
						placeholder="请输入验证码"
						maxLength={6}
						minLength={6}
						pattern="[0-9]{6}"
						type="tel"
						className="my-input my-clear2"
						{...getFieldProps("verifyCode")}
					>
						验证码
						<span className="get-code" onClick={this.getMsgCode}>
							{isClick ? (hasSendCode ? "重新发送" : "获取验证码") : countDown}
						</span>
					</InputItem>
					<div
						className="agree-wrapper"
						style={{ display: this.props.lnid == "802" ? "none" : "block" }}
					>
						<a className="huise">查看</a>
						<a className="xieyi" onClick={e => this.openContract(e, "pay")}>
							《支付连连银通银行卡支付服务协议》
						</a>
					</div>
					{quickShow && (
						<div className="quick">
							<div className="quick-title">
								<span>快速绑卡</span>
								<i onClick={this.closeQuick}></i>
							</div>
							<div className="quick-content">
								<div className="content-title-infor">最近解绑的卡</div>
								<div className="quick-list-content">
									{quckBankList &&
										quckBankList.length > 0 &&
										quckBankList.map(item => (
											<div
												key={item.accountNo}
												className="card-content"
												onClick={() => this.quickBandCard(item)}
											>
												<img src={item.logUrl} alt="" className="item-img" />
												<div className="item-desc">
													<p className="item-name">{item.bankName}</p>
													<p className="item-type">储蓄卡</p>
													<p className="item-card">{item.accountNoEncrypt}</p>
												</div>
												<div className="quick-use">使用</div>
											</div>
										))}
								</div>
							</div>
							<Button onClick={this.saveBank}>同意协议并添加</Button>
						</div>
					)}
					<Modal
						visible={isVisible}
						transparent
						maskClosable={true}
						title="银行卡支持列表"
						closable={true}
						onClose={() => this.toggleVisible(false)}
						className="bank-list-modal"
					>
						<div style={{ height: 300, overflow: "scroll" }}>
							{supportedBankList.map(item => (
								<BankItem item={item} key={Math.random()} />
							))}
						</div>
					</Modal>

					{isHiddenBotton ||
						(!quickShow && (
							<Button onClick={this.saveBank}>同意协议并添加</Button>
						))}
				</div>
			</MainLayout>
		);
	}
}
export default createForm()(BankManageAdd);
